from django.test import TestCase
from .models import UserInfo
from django.contrib.auth.models import Group, Permission
from django.db.models.deletion import ProtectedError


class UserInfoDeletionTest(TestCase):
    def setUp(self):
        """初始化测试数据"""
        # 创建用户实例
        self.user = UserInfo.objects.create(
            username="testuser",
            phone="13800138000",
            password="TestPass123"
        )

        # 创建用户组并建立关联
        self.group = Group.objects.create(name="TestGroup")
        self.user.groups.add(self.group)

        # 创建权限并关联到用户
        self.permission = Permission.objects.get(codename="add_userinfo")
        self.user.user_permissions.add(self.permission)

    def test_delete_user_with_groups(self):
        """测试删除用户及其关联组"""
        # 执行删除操作
        self.user.delete()

        # 验证用户是否删除成功
        self.assertFalse(UserInfo.objects.filter(id=self.user.id).exists())

        # 验证中间表关联是否级联删除
        self.assertFalse(self.group.UserInfo_set.exists())  #

        # 验证权限中间表是否级联删除
        self.assertFalse(self.user.user_permissions.exists())  #

    def test_bulk_delete_with_queryset(self):
        """测试批量删除"""
        # 创建多个用户
        UserInfo.objects.bulk_create([
            UserInfo(username=f"user{i}", phone=f"138000{i}")
            for i in range(5)
        ])

        # 批量删除
        UserInfo.objects.all().delete()  #

        self.assertEqual(UserInfo.objects.count(), 0)
        self.assertEqual(Group.objects.get().UserInfo_set.count(), 0)  #

    def test_protected_relation_handling(self):
        """测试外键保护机制"""
        # 创建受保护的外键关联
        protected_group = Group.objects.create(name="ProtectedGroup")
        self.user.groups.add(protected_group)

        # 尝试删除受保护组时会触发异常
        with self.assertRaises(ProtectedError):  #
            protected_group.delete()
